package demo0512;

import java.io.*;
 import java.util.ArrayList;
 import java.util.List;

 public class Employee {
     private String name;
     private int age;
     private double salary;

     public Employee(String name, int age, double salary) {
         this.name = name;
         this.age = age;
         this.salary = salary;
     }

     // Getter方法
     public String getName() { return name; }
     public int getAge() { return age; }
     public double getSalary() { return salary; }

     @Override
     public String toString() {
         return "姓名：" + name +
                 "，年龄：" + age +
                 "，薪资：" + salary;
     }
     public static void writeEmployeesToFile(List<Employee> employees, String filePath) {
         try (FileOutputStream fos = new FileOutputStream(filePath);
              OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
              BufferedWriter writer = new BufferedWriter(osw)) {

             for (Employee emp : employees) {
                 writer.write(emp.getName() + "," + emp.getAge() + "," + emp.getSalary());
                 writer.newLine();
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
     public static List<Employee> readEmployeesFromFile(String filePath) {
         List<Employee> employees = new ArrayList<>();
         try (FileInputStream fis = new FileInputStream(filePath);
              InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
              BufferedReader reader = new BufferedReader(isr)) {

             String line;
             while ((line = reader.readLine()) != null) {
                 String[] parts = line.split(",");
                 if (parts.length == 3) {
                     String name = parts[0];
                     int age = Integer.parseInt(parts[1]);
                     double salary = Double.parseDouble(parts[2]);
                     employees.add(new Employee(name, age, salary));
                 }
             }
         } catch (IOException e) {
             e.printStackTrace();
         }
         return employees;
     }

     public static void main(String[] args) {
         List<Employee> employees = new ArrayList<>();
         employees.add(new Employee("张三", 25, 8000.0));
         employees.add(new Employee("李四", 30, 12000.0));
         employees.add(new Employee("王五", 35, 15000.0));
         String filePath = "employees.txt";
         writeEmployeesToFile(employees, filePath);
         System.out.println("员工信息已写入文件：" + filePath);
         List<Employee> readEmployees = readEmployeesFromFile(filePath);
         System.out.println("\n从文件读取的员工信息：");
         for (Employee emp : readEmployees) {
             System.out.println(emp);
         }
     }
 }